package org.ly.uap.client.proxy;

import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;

public abstract class AbstractEncryptedProxyGrantingTicketStorageImpl
        implements ProxyGrantingTicketStorage {
    public static final String DEFAULT_ENCRYPTION_ALGORITHM = "DESede";
    private Key key;
    private String cipherAlgorithm = "DESede";

    public final void setSecretKey(String key) throws NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException {
        this.key = SecretKeyFactory.getInstance(this.cipherAlgorithm).generateSecret(new DESedeKeySpec(key.getBytes()));
    }

    public final void setSecretKey(Key key) {
        this.key = key;
    }

    public final void setCipherAlgorithm(String cipherAlgorithm) {
        this.cipherAlgorithm = cipherAlgorithm;
    }

    public final void save(String proxyGrantingTicketIou, String proxyGrantingTicket) {
        saveInternal(proxyGrantingTicketIou, encrypt(proxyGrantingTicket));
    }

    public final String retrieve(String proxyGrantingTicketIou) {
        return decrypt(retrieveInternal(proxyGrantingTicketIou));
    }

    protected abstract void saveInternal(String paramString1, String paramString2);

    protected abstract String retrieveInternal(String paramString);

    private String encrypt(String value) {
        if (this.key == null) {
            return value;
        }

        if (value == null) {
            return null;
        }
        try {
            Cipher cipher = Cipher.getInstance(this.cipherAlgorithm);
            cipher.init(1, this.key);
            return new String(cipher.doFinal(value.getBytes()));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    private String decrypt(String value) {
        if (this.key == null) {
            return value;
        }

        if (value == null) {
            return null;
        }
        try {
            Cipher cipher = Cipher.getInstance(this.cipherAlgorithm);
            cipher.init(2, this.key);
            return new String(cipher.doFinal(value.getBytes()));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
}
